<template>
  <div>
    <el-row>
      <el-col :span="24" align="right">
        <el-button type="primary" @click="addProjectBtn()">关联项目</el-button>
      </el-col>
    </el-row>
    <Table :tableArr="projectList" :pagination="data.page" :columns="data.columns" :isCheckbox="true"
           :total="data.page.total" :dataSources="true" :fixed="true">
      <template #operate="{ row }">
        <el-button size="small" type="danger" @click="handleDelete(row)">取消关联</el-button>
      </template>
    </Table>



    <!-- 项目弹窗 -->
    <el-dialog v-model="Visible" width="900px" top="17vh" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="项目选择" name="first">
              <div class="search-box">
                <el-input v-model="xiangmuParams.projectName" placeholder="请输入" class="input-with-select"
                          style="width: 300px">
                  <template #append>
                    <el-button type="primary" @click="open">搜索</el-button>
                  </template>
                </el-input>
              </div>
              <el-table :data="options.xiangmuList" style="width: 100%" border
                        @selection-change="handleSelectionChange1">
                <el-table-column type="selection" width="40" />
                <el-table-column prop="projectName" label="项目名称" />
                <el-table-column prop="projectNumber" label="项目编号" />
                <el-table-column prop="departmentName" label="关联部门" />
                <el-table-column prop="projectLeaderName" label="项目负责人" />
                <el-table-column prop="projectYear" label="立项年份" />
              </el-table>
              <div class="example-pagination-block">
                <el-pagination background layout="prev, pager, next ,total,sizes,jumper" :total="options.total"
                               :page-size="xiangmuParams.size" @current-change="handleCurrentChange"
                               @size-change="handleSizeChange" />
              </div>
            </el-tab-pane>
          </el-tabs>
          <div class="handle">
            <el-button color="#626aef" @click="closeProject">关闭</el-button>
            <el-button type="primary" @click="toHandle1">关联</el-button>
          </div>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts">
import common from '@/views/science/common/common.json'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { tips } from '@/views/science/components/tips/tips'
import { computed, reactive, ref, watch ,onMounted} from 'vue'
import { useStore } from 'vuex'
import { delectProject } from '../../api/hignEnd'
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import {projectManagementListPage} from "@/views/science/technologyStrength/api/technologyStrength";
import Api from "@/views/science/api/profess";

export default {
  components: {
    Table,
    SelectOption
  },
  emits: {
    dataChange: null,
    projectParams: null,
  },
  props: {
    projects: {
      type: Array,
      required: true,
    }
  },
  setup(props, { emit }) {
    const store = useStore()
    const selectedIds = ref()
    const data = reactive({
      columns: common.platformProjectHeaderxiangmu,
      activeName: ref('first'),
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      projectDia: false,
      unitSelet: computed(() => store.state.technologyStrength.unitSelet),
      projectSelect: computed(() => store.state.technologyStrength.projectSelect),
    })
    const projectList = ref(props.projects ? props.projects : [])


    watch(props, (newValue) => {
      projectList.value = newValue.projects || [];
    });

    // 弹窗中的选择
    let options = reactive({
      xiangmuList: [], //项目列表
      projectList: [],
      contractList: [],
      total: 0,
      isHightPayList: [
        { text: '否', value: '1', },
        { text: '是', value: '0', },
      ],
    })
    let Visible = ref(false)
    //项目搜索参数
    let xiangmuParams = reactive({
      projectName: '',
      projectNumber: '',
      createOrgId: '',
      level: '',
      current: 1,
      size: 10,
      projectCategory: '1',
    })
    //项目列表
    let open = async () => {
      const res = await projectManagementListPage(xiangmuParams)
      const rs = res.data.data
      options.xiangmuList = rs.records
      options.total = rs.total
      Visible.value = true
    }
    //改变页码
    const handleCurrentChange = (e) => {
      xiangmuParams.current = e
      open()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      xiangmuParams.size = e
      open()
    }
    let changeList = ref([])
    let activeName = ref('first')
    let isShow = ref(false)
    let isProject = ref(false)
    let select1 = ref([]) //项目

    let handleSelectionChange1 = (val) => {
      select1.value = val
    }
    const closeProject = () => {
      Visible.value = false;
      select1.value = []
    }
    const toHandle1 = () => {
      if (select1.value.length != 1) {
        tips('请选择一项关联', 'warning')
        return
      } else {
        let obj: Record<string, any> = select1.value[0];
        if (projectList.value.some(t => t.projectId === obj.projectId)) {
          Visible.value = false;
          return;
        }
        emit('projectParams', [getLineData(obj), ...projectList.value]);
        Visible.value = false
      }
    }
    Api.getProjectList().then((res) => {
      options.projectList = res.data.data;
    })
    const getLineData = (obj: Record<string, any>) => ({
      projectId: obj.projectId || obj.id,
      projectName: obj.projectName,
      unitld: obj.unitld || obj.department,
      unitName: obj.unitName || obj.departmentName,
    })

    const findItemNested = (arr, itemId, nestingKey) => (
        arr.reduce((a, item) => {
          if (a) return a;
          if (item.id === itemId) return item;
          if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
        }, null)
    );

    const addProjectBtn = async () => {
      const res = await projectManagementListPage(xiangmuParams)
      const rs = res.data.data
      options.xiangmuList = rs.records
      options.total = rs.total
      Visible.value = true
    }

    const handleDelete = async (row) => {
      const index = projectList.value.findIndex(t => t.projectId === row.projectId);
      if (index > -1) {
        const list = projectList.value.slice(0, index)
          .concat(projectList.value.slice(index + 1));
        emit('projectParams', list);
      }
    }

    return {
      data,
      projectList,
      selectedIds,
      handleDelete,
      addProjectBtn,
      handleCurrentChange,
      handleSizeChange,
      toHandle1,
      Visible,
      handleSelectionChange1,
      changeList,
      activeName,
      isShow,
      isProject,
      xiangmuParams,
      options,
      closeProject,
      open
    }
  },
}
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  display: none;
}

.el-select {
  width: 100%;
  margin: 0;
}
</style>
